package com.iwhalecloud.bss.kite.cucc.web;

import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.kite.common.cache.KiteRedisCache;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.DcSystemParamCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcSystemParam;
import com.iwhalecloud.bss.kite.web.util.PrometheusKey;
import com.ztesoft.common.logger.api.ZLogger;
import com.ztesoft.common.logger.factory.ZLoggerFactory;
import io.prometheus.client.Collector;
import io.prometheus.client.Gauge;
import io.prometheus.client.GaugeMetricFamily;
import io.prometheus.client.exporter.HTTPServer;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

public class HostMetric {
    private final static ZLogger LOGGER = ZLoggerFactory.getLogger(HostMetric.class, KeyConsts.LOG_MODULE);

    private static HostMetric hostMetric = new HostMetric();
    private static KiteRedisCache redisCache = new KiteRedisCache("PrometheusCache");
    private static Map<String,Gauge> gaugeMap = new HashMap<>();
    private HostMetric() {

    }

    private ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1,new CustomizableThreadFactory("HostMetric-Executor"));
    private final static long DELAY = 5 * 1000;
    private final static Integer SCANTIME = 90 * 1000;
    public static HostMetric getInstance() {
        return hostMetric;
    }

    private static String[] labels = {"hostip"};

//    private static final Gauge kite_sys_exception = Gauge.build()
//        .name("outsysa_kite_sysexception")
//        .help("Description of 极简系统异常")
//        .labelNames(labels)
//        .register();
//    private static final Gauge kite_interface_exception = Gauge.build()
//        .name("outsysa_kite_infexception") //Metric Name
//        .help("Description of 接口调用异常") //对该Metric的描述
//        .labelNames(labels) //array形式的labelname
//        .register();
//    private static final Gauge kite_interface_error = Gauge.build()
//        .name("outsysa_kite_interface_error") //Metric Name
//        .help("Description of 接口调用异常") //对该Metric的描述
//        .labelNames(labels) //array形式的labelname
//        .register();
    private static final Gauge kite_hsf_full_exception = Gauge.build()
        .name("outsysa_kite_hsf_full_exception") //Metric Name
        .help("kite_hsf_full_exception") //对该Metric的描述
        .labelNames(labels) //array形式的labelname
        .register();

    private static void getData() {

        JSONObject prometheusCache = (JSONObject) JSONObject.parse(redisCache.get(KiteRedisCache.namespace, redisCache.getPrefixKey(), ""));
        if (null != prometheusCache) {
            prometheusCache.entrySet().forEach(entry -> {
                AtomicReference<Double> error = new AtomicReference<>((double) 0);
                String key = entry.getValue().toString();
                String code = key.split("\\$")[1];
                String ips = KiteStringUtils.getIps(key).stream().collect(Collectors.joining(","));
//                kite_sys_exception.labels(ips).set(error.get());
//                kite_interface_exception.labels(ips).set(error.get());
//                kite_interface_error.labels(ips).set(error.get());
                kite_hsf_full_exception.labels(ips).set(error.get());
                if (redisCache.get(KiteRedisCache.namespace, redisCache.getPrefixKey(), key) != null) {
                    DcSystemParam dcSystemParam =DcSystemParamCache.get(code);
                    if(null!=dcSystemParam){
                        if (key.indexOf("HSFException")>0) {
                            error.set(Double.valueOf(redisCache.get(KiteRedisCache.namespace, redisCache.getPrefixKey(), key)));
                            kite_hsf_full_exception.labels(ips).set(error.get());
                        } else {
                            error.set(Double.valueOf(redisCache.get(KiteRedisCache.namespace, redisCache.getPrefixKey(), key)));
                            Gauge gauge=  getGauge(dcSystemParam);
                            gauge.labels(ips).set(error.get());
                        }
                    }else {
                        LOGGER.info("数据库未配置Prometheus！！！请配置。");
                    }
                }
            });
        }

    }

    public void startPrometheus() {
        try {
            //端口可自定义
            new HTTPServer(6067);
            scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
                @Override
                public void run() {
                    LOGGER.info("Prometheus 扫描");
                    getData();
                }
            }, DELAY, SCANTIME, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            LOGGER.info(e.getMessage());
        }
    }
    private static Gauge getGauge(DcSystemParam dcSystemParam){
        String[] desc = dcSystemParam.getParamDesc().split(":");
        Gauge gauge =gaugeMap.get(dcSystemParam.getParamDesc());
        if(null==gauge){
            gaugeMap.put(dcSystemParam.getParamDesc(),Gauge.build().name(desc[0]).help(desc[1]).labelNames(labels).register());
        }else{
            return gauge;
        }
        return gaugeMap.get(dcSystemParam.getParamDesc());
    }
}

